# coding:utf-8

import os
import json

from gevent import monkey
def stub(*args, **kwargs):  # pylint: disable=unused-argument
    pass
monkey.patch_all = stub
import grequests
from wechatpy import WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from wechatpy.client.api import WeChatTag, WeChatUser
from wechatpy.oauth import WeChatOAuth
from wechatpy.pay import WeChatPay
from wechatpy.pay.api import WeChatOrder
from wechatpy.pay.api.jsapi import WeChatJSAPI

from common.utils import redis_client

from .log import Log

APP_ID = os.environ.get('wechat_app_id') or 'wx0a9dc0a3a4977226'
APP_SECRET = os.environ.get('wechat_app_secret') or '7be3a2742fcaca35152fee91ccbdcc05'
APP_TOKEN = os.environ.get('wechat_app_token') or 'notecode0629'
APP_AESKEY = os.environ.get('wechat_app_aeskey') or 'GnJHjWrm62LPSm63BxTyUodcnqG5qRQxz61pLXyVwS2'

# wx pay
PAY_KEY = os.environ.get('wx_pay_key') or 'aCnKIuIGDMMbcCVbpyoSfDzJvvTo08Vh'
MCHT_ID = os.environ.get('wx_mcht_id') or '1485421962'

# 微信移动应用相关信息
MOBILE_APP_ID = os.environ.get('wechat_mobile_app_id') or 'wx5d89b6914e7dc26f'
MOBILE_APP_SECRET = os.environ.get('wechat_mobile_app_secret') or '617603ebed7cc286d4cdea581014d6b9'
MOBILE_MCHT_ID = os.environ.get('wx_mobile_mcht_id') or '1493293642'
MOBILE_PAY_KEY = os.environ.get('wx_mobile_pay_key') or 'aCnKIuIGDMMbcCVbpyoSfDzJvvTo08Vh'

# 微信实例
session_interface = RedisStorage(redis_client, prefix='opc_wechat')
client = WeChatClient(APP_ID, APP_SECRET, session=session_interface)
tag_client = WeChatTag(client=client)
user_client = WeChatUser(client=client)

# 微信支付实例
wx_pay_client = WeChatPay(APP_ID, PAY_KEY, MCHT_ID)
wx_js_api = WeChatJSAPI(client=wx_pay_client)
wx_order_api = WeChatOrder(client=wx_pay_client)

wx_mobile_pay_client = WeChatPay(MOBILE_APP_ID, MOBILE_PAY_KEY, MOBILE_MCHT_ID)
wx_mobile_order_api = WeChatOrder(client=wx_mobile_pay_client)


def get_access_token():
    """
    created by chenhj at 2017/7/26
    使用wechatpy内置的缓存, 详见上边的client实例声明, 传入了redis实例
    """
    return client.access_token


def send_template_message(openid, template_id, data, url):
    """
    created by chenhj at 2017/7/26
    返回一个异步发送模板消息的实例(并还没有真正的发送请求出去), 需要上层调用grequests.map()方法
    """
    access_token = get_access_token()
    return grequests.post(
        'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}'.format(
            access_token=access_token
        ),
        headers={'Content-Type': 'application/json'},
        data=json.dumps({
            "touser": openid,
            "template_id": template_id,
            "url": url,
            "data": data
        })
    )


def create_user_tags(tag_name):
    """
    created by chenhj at 2017/8/11
    创建标签
    @:return {'id': 110, 'name': 'test'}
    """
    return tag_client.create(tag_name)


def get_user_tags():
    """
    created by chenhj at 2017/8/2
    获取所有用户标签
    """
    return {'tags': tag_client.get()}


def update_users_tag(openid_list, tag_id):
    """
    created by chenhj at 2017/8/2
    批量给微信用户打上标签
    """
    return tag_client.tag_user(tag_id, openid_list)


def sync_wechat_menu(menu_json):
    """
    created by chenhj at 2017/8/3
    同步菜单到公众号上
    """
    import requests
    access_token = get_access_token()
    res = requests.post(
        'https://api.weixin.qq.com/cgi-bin/menu/create?access_token={access_token}'.format(
            access_token=access_token
        ),
        headers={'Content-Type': 'application/json'},
        data=json.dumps(menu_json, ensure_ascii=False).encode('utf-8')
    )
    return res.json()


def get_wxuser_info(openid):
    """
    created by chenhj at 2017/8/4
    """

    return user_client.get(openid)


def get_wxuser_list():
    """
    created by chenhj at 2017/8/4
    获取所有微信关注用户列表
    """
    return user_client.get_followers()


def generate_wechat_oauth(redirect_uri):
    """
    created by chenhj at 2017/9/11

    """
    return WeChatOAuth(
        app_id=APP_ID,
        secret=APP_SECRET,
        redirect_uri=redirect_uri
    )


def update_wxuser_remark(openid, remark):
    """
    created by chenhj at 2017/8/11

    """
    return user_client.update_remark(openid, remark)


def exception_handler(request, exception):
    Log.info(exception)


def grequest_send(req_set):
    """
    created by chenhj at 2017/7/26

    """
    res = grequests.map(req_set, exception_handler=exception_handler)
    for each in res:
        try:
            Log.info(each.status_code)
            Log.info(each.json())
        except:
            pass


if __name__ == '__main__':
    # print(get_access_token())
    # wx_openid = 'o1DGe1OMj8V0lZd0ppgMfPDrE1ao'
    # wx_template_id = 'jLSkw44QF9SSkrBqH-MGDIS-7zDjQsn4krs0r7gxfoo'
    # wx_data = """
    # {
    #     "first": {
    #         "value": "测试发送模板消息",
    #         "color": "#173177"
    #     },
    #     "tradeDateTime": {
    #         "value": "2017-07-30",
    #         "color": "#173177"
    #     },
    #     "orderType": {
    #         "value": "新订单",
    #         "color": "#173177"
    #     },
    #     "customerInfo": {
    #         "value": "抢单成功后可见",
    #         "color": "#173177"
    #     },
    #     "orderItemName": {
    #         "value": "预计费用"
    #     },
    #     "orderItemData": {
    #         "value": "12元",
    #         "color": "#173177"
    #     },
    #     "remark": {
    #         "value": "\\n客户在线, 速戳立即抢单↓↓↓",
    #         "color": "#4785F9"
    #     }
    # }
    # """
    # wx_url = 'https://wx.wanpinghui.com/demanddetail.html?demand=6734'
    #
    # post_data = {
    #     'openid': wx_openid,
    #     'template_id': wx_template_id,
    #     'data': json.loads(wx_data),
    #     'url': wx_url
    # }
    #
    # r = set()
    # r.add(send_template_message(**post_data))
    # grequest_send(r)
    print(create_user_tags('test'))
